package main

import (
	"bufio"
	"io"
	"ipbc0/api"
	"ipbc0/core"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

// go build -ldflags "-H windowsgui"
func main() {
	conf := readConf()
	core.InitCtx(conf)

	http.HandleFunc("/", route)

	log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(conf.HTTPServerPort), nil))
}

func route(w http.ResponseWriter, r *http.Request) {
	uri := r.RequestURI
	log.Println(uri)
	if uri == "/net0/api/task/pcm/start" {
		api.StartTask(w, r)
	} else if uri == "/net0/api/task/pcm/stop" {
		api.StopTask(w, r)
	} else if uri == "/net0/api/speech/check" {
		api.CheckSpeech(w, r)
	} else if strings.HasPrefix(uri, "/net0/api/speech/open/") {
		api.OpenSpeech(w, r)
	} else if strings.HasPrefix(uri, "/net0/api/speech/close/") {
		api.CloseSpeech(w, r)
	} else if uri == "/net0/api/deviceControl/list" {
		api.ListDevice(w, r)
	} else if uri == "/net0/api/deviceControl/heartbeatAll" {
		api.HeartbeatAll(w, r)
	}
}

func readConf() (conf *core.Conf) {
	conf = &core.Conf{
		HTTPServerPort: 10061,
		UDPServerPort:  9014,
		TCPServerPort:  10068,
		AudioFilePath:  "D:\\sof\\upload",
		TestMode:       true,
	}

	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}

	f, err := os.Open(dir + string(os.PathSeparator) + "ipbc0.conf")
	if err != nil {
		log.Println(err)
	} else if f != nil {
		reader := bufio.NewReader(f)
		for {
			data, _, err := reader.ReadLine()
			if err != nil || io.EOF == err {
				break
			}

			line := string(data)
			line = strings.Replace(line, "\n", "", -1)
			line = strings.Replace(line, "\r", "", -1)

			if line != "" && !strings.HasPrefix(line, "#") {
				strs := strings.Split(line, "=")
				if len(strs) > 1 {
					for _, str := range strs {
						str = strings.TrimPrefix(str, " ")
						str = strings.TrimSuffix(str, " ")
					}
					if strs[0] == "http-port" {
						port, err := strconv.Atoi(strs[1])
						if err != nil {
							log.Println(err)
						} else {
							conf.HTTPServerPort = port
						}
					} else if strs[0] == "udp-port" {
						port, err := strconv.Atoi(strs[1])
						if err != nil {
							log.Println(err)
						} else {
							conf.UDPServerPort = port
						}
					} else if strs[0] == "tcp-port" {
						port, err := strconv.Atoi(strs[1])
						if err != nil {
							log.Println(err)
						} else {
							conf.TCPServerPort = port
						}
					} else if strs[0] == "audio-file-path" {
						if strs[1] != "" {
							conf.AudioFilePath = strs[1]
						}
					} else if strs[0] == "test-mode" {
						testMode, err := strconv.ParseBool(strs[1])
						if err != nil {
							log.Println(err)
						} else {
							conf.TestMode = testMode
						}
					}
				}
			}
		}
	}

	defer func() {
		if f != nil {
			f.Close()
		}
	}()

	log.Println("conf: " + conf.String())
	return
}
